﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace Qing.QLoggers
{
    class TextLogger : QLogger
    {
        public TextLogger()
        {
        }

        void CheckDirectory(string file)
        {
            file = (file + "").Replace("/", Path.DirectorySeparatorChar + "");
            var f = new FileInfo(file);
            if (!f.Directory.Exists)
            {
                var dirStack = new Stack<DirectoryInfo>();
                for (var dir = f.Directory; dir != null; dir = dir.Parent) dirStack.Push(dir);
                while (dirStack.Count > 0) dirStack.Pop().Create();
            }
        }

        void Write(string file, string txt)
        {
            file = (file + "").Replace("/", Path.DirectorySeparatorChar + "");
            var f = new FileInfo(file);
            File.AppendAllText(f.FullName, txt, Encoding.Default);
        }

        string Format(QLogInfo logInfo)
        {
            var res = logInfo.ToString();
            res = res.Replace("\r", "").Replace("\n", "");
            return res + Environment.NewLine;
        }

        protected override void Write(QLogInfo logInfo)
        {
            var source = Source;
            CheckDirectory(source);
            var line = Format(logInfo);
            this.Write(source, line);
        }
    }
}
